package com.xqiapp.jsp.config;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

/**
 * Created by rwrwd7 on 2017/9/21.
 * DataSourceBuilder.create().type(dataSourceType).build();
 */
@Component
@Order(-1)
@Aspect
public class DataSourceAspect {

    @Pointcut("execution(* com.xqiapp.service..*(..))")
    public void aspect() {}

    @Before("aspect()")
    public void doBefore(JoinPoint point) throws Throwable {
        final MethodSignature methodSignature = (MethodSignature) point.getSignature();
        Method method = methodSignature.getMethod();
        DataSourceTarget dataSourceTarget = method.getAnnotation(DataSourceTarget.class);
        if(method.getDeclaringClass().isInterface()) {
            method = point.getTarget().getClass().getMethod(method.getName(), method.getParameterTypes());
        }
        dataSourceTarget = method.getAnnotation(DataSourceTarget.class);
        String routeKey = DataSourceTarget.DEFAULT;
        if(null != dataSourceTarget) {
            routeKey = dataSourceTarget.routeKey();
        }
        DataSourceRouteHolder.setDataSourceRouteKey(routeKey);
    }

    @After("aspect()")
    public void doAfter() {
        DataSourceRouteHolder.clearDataSourceRouteKey();
    }

}
